<template>
  <div class="admin-lesson-manage">
    <h2>网课管理</h2>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="分类">
          <el-select v-model="categoryId" placeholder="全部分类" clearable @change="handleFilter" style="min-width: 200px;">
            <el-option
              v-for="item in categorys"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="keyword" placeholder="课程标题或内容" clearable style="min-width: 220px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 课程列表 -->
    <el-table :data="lessons" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="课程标题" width="200">
        <template #default="scope">
          <div class="title-with-cover">
            <el-image 
              :src="scope.row.coverImg" 
              fit="cover"
              style="width: 40px; height: 40px; margin-right: 10px;"
              :preview-src-list="[scope.row.coverImg]">
            </el-image>
            {{ scope.row.title }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类" width="150"></el-table-column>
      <el-table-column prop="createUserName" label="创建者" width="120"></el-table-column>
      <el-table-column prop="state" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.state === '已发布' ? 'success' : 'info'">
            {{ scope.row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="previewLesson(scope.row)">
            预览
          </el-button>
          <el-button 
            :type="scope.row.state === '已发布' ? 'warning' : 'success'" 
            size="small" 
            @click="toggleLessonState(scope.row)">
            {{ scope.row.state === '已发布' ? '下架' : '发布' }}
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="confirmDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="课程预览" width="70%">
      <div v-if="currentLesson" class="lesson-preview">
        <h3>{{ currentLesson.title }}</h3>
        <div class="meta-info">
          <span class="meta-item">
            <strong>分类：</strong>
            <el-tag size="small" type="success">{{ currentLesson.categoryName }}</el-tag>
          </span>
          <span class="meta-item"><strong>创建者：</strong>{{ currentLesson.createUserName }}</span>
          <span class="meta-item">
            <strong>状态：</strong>
            <el-tag :type="currentLesson.state === '已发布' ? 'success' : 'info'" size="small">
              {{ currentLesson.state }}
            </el-tag>
          </span>
        </div>
        <div class="preview-video">
          <video 
            v-if="currentLesson.videoUrl" 
            :src="currentLesson.videoUrl" 
            controls
            preload="metadata"
            style="width: 100%; max-height: 400px;">
            您的浏览器不支持视频播放
          </video>
        </div>
        <div class="preview-content" v-html="currentLesson.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminLessonListService, adminUpdateLessonStateService, lessonCategoryListService } from '@/api/lesson'
import { formatDateTime } from '@/utils/format'
import { useTokenStore } from '@/stores/token'

// 状态变量
const lessons = ref([])
const total = ref(0)
const loading = ref(false)
const categorys = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const categoryId = ref(null)
const keyword = ref('')
const previewVisible = ref(false)
const currentLesson = ref(null)

// 获取课程列表
const fetchLessons = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      categoryId: categoryId.value || null,
      keyword: keyword.value || ''
    }
    
    const result = await adminLessonListService(params)
    
    if (result.code === 0) {
      const data = result.data
      lessons.value = data.items || []
      total.value = data.total || 0
      
      // 处理课程分类名称
      processCategoryNames()
    } else {
      ElMessage.error(result.msg || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 处理课程分类名称
const processCategoryNames = () => {
  for (let lesson of lessons.value) {
    let category = categorys.value.find(c => c.id == lesson.categoryId)
    lesson.categoryName = category ? category.categoryName : '未分类'
  }
}

// 获取课程分类
const fetchCategories = async () => {
  try {
    const result = await lessonCategoryListService()
    if (result.code === 0) {
      categorys.value = result.data || []
    } else {
      ElMessage.error(result.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchLessons()
}

// 重置筛选
const resetFilter = () => {
  categoryId.value = null
  keyword.value = ''
  currentPage.value = 1
  fetchLessons()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchLessons()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchLessons()
}

// 预览课程
const previewLesson = (lesson) => {
  currentLesson.value = lesson
  previewVisible.value = true
}

// 切换课程状态
const toggleLessonState = async (lesson) => {
  const newState = lesson.state === '已发布' ? '草稿' : '已发布'
  const actionText = newState === '已发布' ? '发布' : '下架'
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionText}该课程吗？`,
      `${actionText}课程`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const result = await adminUpdateLessonStateService(lesson.id, newState)
    
    if (result.code === 0) {
      ElMessage.success(`课程${actionText}成功`)
      lesson.state = newState
    } else {
      ElMessage.error(result.msg || `课程${actionText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`课程${actionText}失败:`, error)
      ElMessage.error(`课程${actionText}失败`)
    }
  }
}

// 确认删除课程
const confirmDelete = async (lesson) => {
  try {
    await ElMessageBox.confirm(
      '删除后将无法恢复，确定要删除该课程吗？',
      '删除课程',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用现有的删除接口
    const result = await fetch(`/api/lesson?id=${lesson.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': useTokenStore().token
      }
    }).then(res => res.json())
    
    if (result.code === 0) {
      ElMessage.success('删除课程成功')
      fetchLessons() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '删除课程失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

// 页面初始化
onMounted(() => {
  fetchCategories().then(() => {
    fetchLessons()
  })
})
</script>

<style scoped>
.admin-lesson-manage {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.title-with-cover {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.meta-info {
  margin: 10px 0;
  color: #606266;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-info .meta-item {
  margin-right: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.meta-info .meta-item strong {
  color: #303133;
}

.preview-video {
  margin: 15px 0;
}

.preview-content {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style> 